<template>
  <div class="createExpenseForm">
    <group label-width="1rem" label-align="left" gutter="0">
      <x-input v-if="this.$route.query.id" title="工单编号" v-model="workOrderCode" :disabled="true">
        <!--<img slot="right-full-height" src="~assets/images2/icon_zuojian@2x.png">-->
      </x-input>
      <selector v-else title="工单编号" v-model="workOrderCode" @on-change="getRequest"
                :options="workOrderList"></selector>
      <cell title="报销单拍照" @click.native="showPopup" is-link>
        <span slot="child" class="child">{{formFileStore.length}}张图片</span>
        <img slot="after-title" width="20" style="margin-right:5px"
             src="~assets/images2/icon_shangchuan@3x.png"/>
      </cell>
    </group>
    <tab active-color="#43A2FE" style="margin-top: 10px" v-model="currentIndex">
      <tab-item v-for="(item, index) in contentList" :key="index" :selected="index===currentIndex">
        <span v-if="index===currentIndex&&contentList.length > 1">明细{{ (index+1) }} <span
          @click="removeTab(index)"> <icon type="cancel"></icon></span></span>
        <span v-else="index ===currentIndex">明细{{ (index+1)  }}</span>
      </tab-item>
    </tab>
    <swiper ref="swiper" :threshold="10000" :min-moving-distance="10000" v-model="currentIndex" :show-dots="false" @on-index-change="setHeight">
      <swiper-item v-for="(item, index) in contentList" :key="index">
        <CostForm v-if="index==currentIndex" ref="swiper_item" v-on:heightChange='setHeight' :current="currentIndex"
                  :exitRequestList="exitRequestList"
                  :formdata="item"></CostForm>
      </swiper-item>
    </swiper>
    <div class="add-item blue" @click="addTab">
      添加费用
    </div>
    <div class="clearfix"></div>
    <group label-width="1rem" label-align="left">
      <cell title="合计">
        <span slot="after-title">{{allFillAmount}}</span>
      </cell>
    </group>
    <group class="addPerson" gutter="10px">
      <p>初审人</p>
      <span>
        提交人一次性选择好所有的相关初审人,系统将根据选择的初审人流转单据,初审人审批通过后由复核人最终审核
      </span>
      <ol>
        <li v-for="(item,index) in firstTrials" v-if="item.checked">
          <div class="item_box">
            <i class="fa fa-minus-circle" @click="item.checked =false"></i>
            <img src="~assets/images3/user_defualt.jpg" alt="">
            <div>{{item.nickName}}</div>
          </div>
        </li>
        <li>
          <div class="item_box">
            <img src="~assets/images3/icon-ttianjia@3x.png" alt="" @click="addApproval(firstTrials,3)">
          </div>
        </li>
      </ol>
    </group>
    <group class="addPerson" gutter="0">
      <p>复核人</p>
      <ol>
        <li v-for="(item,index) in secondTrials" v-if="item.checked">
          <div class="item_box">
            <i class="fa fa-minus-circle" @click="item.checked =false"></i>
            <img src="~assets/images3/user_defualt.jpg" alt="">
            <div>{{item.nickName}}</div>
          </div>
        </li>
        <li>
          <div class="item_box">
            <img src="~assets/images3/icon-ttianjia@3x.png" alt="" @click="addApproval(secondTrials,4)">
          </div>
        </li>
      </ol>
    </group>
    <flexbox>
      <flexbox-item>
        <x-button type="warn" @click.native="cancelCommit">
          <icon type="cancel"></icon>
          取消
        </x-button>
      </flexbox-item>
      <flexbox-item style="margin-left: 0">
        <x-button type="warn" @click.native="submitExpense(0)">
          <i class="fa fa-file-text-o"></i> 存草稿
        </x-button>
      </flexbox-item>
      <flexbox-item style="margin-left: 0">
        <x-button type="primary" @click.native="submitExpense(1)">
          <icon type="success-circle"></icon>
          提交
        </x-button>
      </flexbox-item>
    </flexbox>
    <div v-transfer-dom>
      <popup v-model="bxdPopup" height="90%">
        <popup-header
          left-text="取消"
          right-text="确认"
          title="报销单图片"
          :show-bottom-border="false"
          @on-click-left="showPopup"
          @on-click-right="showPopup"></popup-header>
        <UploadImage :imgs="formFileStore"></UploadImage>
      </popup>
      <!--<popup v-model="bxdPopup"height="90%">-->
      <!--<div style="height: 30px;text-align: right;line-height: 20px;margin-right: 5px">-->
      <!--<span @click="showPopup" style="line-height: 30px;font-size: 15px">完成</span></div>-->
      <!--<UploadImage :imgs="formFileStore"></UploadImage>-->
      <!--</popup>-->
    </div>
    <div v-transfer-dom>
      <popup v-model="sprPopup" height="90%">
        <popup-header
          left-text="取消"
          right-text="确认"
          :title="approvalList===firstTrials?'选择初审人':'选择复审人'"
          :show-bottom-border="false"
          @on-click-left="addApprovalSure(approvalList)"
          @on-click-right="addApprovalSure"></popup-header>
        <ChoiceApprover :list="approvalList"></ChoiceApprover>
      </popup>
    </div>
  </div>
</template>

<script>
  import {
    Group,
    XInput,
    XTextarea,
    Selector,
    Cell,
    FormPreview,
    Icon,
    XButton,
    Flexbox,
    FlexboxItem,
    Tab,
    TabItem,
    Swiper,
    PopupHeader,
    SwiperItem,
    Popup,
    XSwitch,
    TransferDom,
    Sticky
  } from 'vux';
  import CostForm from './costForm.vue'
  import UploadImage from './uploadImage.vue'
  import ChoiceApprover from './choiceApprover.vue'

  export default {
    name: "createExpenseForm",
    directives: {
      TransferDom
    },
    components: {
      Group, XInput, XTextarea, Selector, Cell, FormPreview, Icon, Sticky,
      XButton, Flexbox, FlexboxItem, Tab, TabItem, Swiper, SwiperItem, PopupHeader,
      CostForm, UploadImage, Popup, XSwitch, ChoiceApprover
    },
    data() {
      return {
        currentIndex: 0,//当前报销单tab
        bxdPopup: false,//报销单照片弹窗
        sprPopup: false,//审批人弹窗
        workOrderList: [],
        fillAmount: 0,
        formFileStore: [],//报销单照片数量
        workOrderCode: '',//工单编号
        contentList: [],//报销单form内容
        firstTrials: [],//初审人列表
        secondTrials: [],//复核人列表
        approvalList: [],//当前选择人列表
        exitRequestList: [],//申请单对应的报销单
      }
    },
    computed: {
      allFillAmount() {
        this.fillAmount = this.contentList.reduce((total, item) => {
          return parseFloat(total || 0) + parseFloat(item.fillFigure || 0);
        }, 0);
        return this._numberComma(this.fillAmount);
      }
    },
    created() {
      this.addTab();
      let params = {engineerId: this.$store.state.user.userInfo.id, systemStatus: '7,8', noPage: true}
      this.$http.get('/work/api/workorder', {params: params}).then(res => {
          if (res.data.data.length == 0) {
            this.$vux.alert.show({
              title: '提醒',
              content: '暂无可报销的工单！',
              onHide: () => {
                this.$router.go(-1)
              }
            })
          }
          this.workOrderList = res.data.data.map(r => {
            return r.code;
          })
        }
      )
    },
    mounted() {
      this.$getUserInfo();
      //进入编辑界面
      if (this.$route.query.id) {
        this.$http.get('/expense/api/expenseForm/' + this.$route.query.id).then(res => {
          // 格式化后端数据至前端
          let object = res.data.data;
          //图片id转path
          object.formFileStore ?this.$http.get('/work/api/upload/byid', {params: {ids: object.formFileStore}}).then(res => {
            this.formFileStore = res.data.data[object.formFileStore];
          }):(this.formFileStore = []);
          //判断工单是否存在申请单
          this.$http.get('/expense/api/RequestForm', {
            params: {
              workOrderCode: object.workOrderCode,
              noPage: true,
            }
          }).then(resp => {
              if (resp.data.data.length > 0) {
                //存在费用申请单，缓存申请单明细
                this.exitRequestList = resp.data.data[0].requestFormItems;
              } else {
                //不存在费用申请单
                this.exitRequestList = [];
              }
              this.id = object.id;
              this.workOrderCode = object.workOrderCode;

              this.fillAmount = object.fillAmount;
              //默认返回的审核人都是已经选中
              object.firstTrials.forEach(item => {
                item.checked = true;
              });
              this.firstTrials = object.firstTrials;
              object.secondTrials.forEach(item => {
                item.checked = true;
              });
              this.secondTrials = object.secondTrials;
              let promisesAll = [];
              object.expenseFormItems.forEach(item => {
                promisesAll.push(new Promise((resolveAll, rejectAll) => {
                  //图片id转path
                  item.invoiceFileStore ? this.$http.get('/work/api/upload/byid?', {params: {ids: item.invoiceFileStore}}).then(res => {
                    item.invoiceFileStore = res.data.data[item.invoiceFileStore];
                  }) : (item.invoiceFileStore = []);
                  item.voucherFileStore ? this.$http.get('/work/api/upload/byid', {params: {ids: item.voucherFileStore}}).then(res => {
                    item.voucherFileStore = res.data.data[item.voucherFileStore];
                  }) : (item.voucherFileStore = []);
                  item.subjectList = JSON.parse(item.subjectContent);
                  item.subjectContent = {};
                  item.count = item.count || '';
                  let promisesItemAll = [];
                  if (item.subjectList.length == 0) {
                    resolveAll();
                  }
                  //费用申请单中存在该明细
                  let exitRequestDetail = false;
                  if (this.exitRequestList.length > 0) {
                    this.exitRequestList.forEach(r => {
                      if (r.subjectCode == item.subjectCode && r.status == 1) {
                        exitRequestDetail = r;
                      }
                    })
                  }
                  item.subjectList.forEach(r => {
                    promisesItemAll.push(new Promise((resolveItemAll, rejectItemAll) => {
                      item.subjectContent[r.key] = r.value;
                      if (r.type === 'select') {
                        if (r.key === 'shipLevel') {
                          this.$http.get(exitRequestDetail ? '/expense/api/shipLevel' : '/expense/api/standard/shipLevel', {
                            params: {
                              subjectCode: item.subjectCode,
                              noPage: exitRequestDetail ? true : false,
                              postLevel: exitRequestDetail ? null : this.$store.state.user.userInfo.postBean.level,
                            }
                          }).then(dic => {
                            if (dic.data.data) {
                              (exitRequestDetail) &&
                              (dic.data.data = dic.data.data.map(item => {
                                return item.shipLevel;
                              }));
                              r.dict = r.key;//特意处理仓位等级没有dict字段
                              item.subjectSelect = item.subjectSelect || {};
                              item.subjectSelect[r.dict] = dic.data.data;
                              resolveItemAll();
                            }
                            else
                              resolveItemAll()
                          });
                        } else {
                          this.$http.get('/account/api/dict', {
                            params: {
                              codeLike: r.dict,
                              include: true,
                              noPage: true,
                              fields: 'id,code,name'
                            }
                          }).then(dic => {
                            if (dic.data.data) {
                              dic.data.data = dic.data.data.map(item => {
                                return item.name;
                              });
                            }
                            item.subjectSelect = item.subjectSelect || {};
                            item.subjectSelect[r.dict] = dic.data.data;
                            resolveItemAll();
                          });
                        }
                      } else {
                        resolveItemAll();
                      }
                    }));
                  });
                  Promise.all(promisesItemAll).then(resp => {
                    resolveAll()
                  });
                }));
              });
              Promise.all(promisesAll).then(() => {
                this.contentList = object.expenseFormItems;
                //确定科目类别之再确定高度
                this.setHeight();
                if(object.status == 4){
                  this.$vux.alert.show({
                    title: '驳回原因',
                    content: "<span style='color: red'>"+object.firstOption+"</span>"
                  })
                }
              })
            }
          )
        })
      }
      else {
        this.setHeight();
      }
    }
    ,
    watch: {}
    ,
    methods: {
      validate() {
        let _is = true;
        for(let ref in this.$refs.swiper_item[0].$refs){
          this.$refs.swiper_item[0].$refs[ref].setTouched();
          this.$refs.swiper_item[0].$refs[ref].validate();
          if(!this.$refs.swiper_item[0].$refs[ref].valid)
            _is = this.$refs.swiper_item[0].$refs[ref].valid
        }
        return _is;
      },
      //获取工单编号对应的申请单
      getRequest() {
        // 重新选择直接置空明细
        this.contentList = [];
        this.currentIndex = 0;
        this.addTab();
        this.setHeight();
        this.$http.get('/expense/api/RequestForm', {
          params: {
            workOrderCode: this.workOrderCode,
            noPage: true,
          }
        }).then(res => {
          if (res.data.data.length > 0) {
            //存在费用申请单，缓存申请单明细
            this.exitRequestList = res.data.data[0].requestFormItems;
          } else {
            //不存在费用申请单
            this.exitRequestList = [];
          }
        })
      }
      ,
      //设置swapper高度
      setHeight() {
        this.$nextTick(() => {
          this.$refs.swiper.xheight = this.$refs.swiper_item[0].$el.clientHeight + 'px'
        })
      }
      ,
      //弹出拍照界面
      showPopup() {
        this.bxdPopup = !this.bxdPopup
      }
      ,
      //关闭申请人界面
      addApprovalSure(list) {
        this.sprPopup = !this.sprPopup;
        if (list) {
          list.forEach(item => {
            item.checked = false;
          })
        }
      }
      ,
      //弹出申请人界面
      addApproval(list, index) {
        //如果请求数据了，就不再请求
        if (list && list.length > 0) {
          this.approvalList = list;
          this.sprPopup = !this.sprPopup;
          return
        }
        let params = {
          departmentId: this.$store.state.user.userInfo.departmentBean.id,
          typeStatus: index,
        };
        //获取对应的申请人ids
        let getList = new Promise((resolve, reject) => {
          this.$http.get('/expense/api/auditConfiguration', {params: params}).then(res => {
              resolve(res.data.data.rows);
            }
          )
        });
        getList.then(data => {
          let userIds = data.map(function (r) {
            return r.userId
          });
          let param = {
            userIds: userIds.join(','),
            include: true,
            fields: 'nickName,id'
          };
          // 获取申请人的详情
          this.$http.get('/expense/api/auditConfiguration/user', {params: param}).then(res => {
              res.data.data.forEach(item => {
                item.checked = false;
                list.push(item)
              });
              this.approvalList = list;
              this.sprPopup = !this.sprPopup;
            }
          )
        });

      }
      ,
      //添加明细
      addTab() {
        if(this.contentList.length>0){
          if(this.validate())
            this.addList();
        }else{
          this.addList();
        }
      }
      ,
      addList(){
        this.contentList.push({
          subject: '',
          subjectCode: '',
          subjectList: [],
          subjectContent: {},
          fillFigure: '',
          state: '',
          subjectName: '',
          count: '',
          subjectSelect: {},
          invoiceFileStore: [],
          voucherFileStore: [],
        });
        this.$nextTick(() => {
          this.currentIndex = this.contentList.length - 1;
        });
      },
      //删除明细
      removeTab(index) {
        this.$vux.confirm.show({
          title: '提醒',
          content: '是否确定删除？',
          onCancel: () => {

          },
          onConfirm: () => {
            if (this.contentList.length > 1) {
              this.contentList.splice(index, 1)
              this.currentIndex = index - 1;//当前报销单tab
            }
          }
        })
      }
      ,
      // 保存/提交审核  格式化前端数据至后端
      submitExpense(index) {
        if (!this.workOrderCode) {
          this.$vux.toast.show({text: '工单必填', type: 'warn'});
          return
        }
        if (this.firstTrials.length <= 0||this.firstTrials.filter(r=>{ return r.checked == true}).length<=0) {
          this.$vux.toast.show({text: '初审人必填', type: 'warn'});
          return
        }
        if (this.secondTrials.length <= 0||this.secondTrials.filter(r=>{ return r.checked == true}).length<=0) {
          this.$vux.toast.show({text: '复审人必填', type: 'warn'});
          return
        }
        // 界面验证规则
        if (!this.validate()) {
          return
        }
        let txt = '';
        this.contentList.forEach((item, index) => {
          if (!item.subjectCode) {
            if (!txt)
              txt = '明细' + (index + 1) + '科目必填'
            return
          }
          if (!item.count) {
            if (!txt)
              txt = '明细' + (index + 1) + '报销数量必填'
            return
          }
          if (!item.fillFigure) {
            if (!txt)
              txt = '明细' + (index + 1) + '报销金额必填'
            return
          }
          if(item.subjectList.length > 0){
            item.subjectList.forEach(r=>{
              if(r.required&&!item.subjectContent[r.key]){
                if (!txt)
                  txt = '明细' + (index + 1) +r.label+ '必填'
                return
              }
            });
          }
        });
        if(txt){
          this.$vux.toast.show({text: txt, type: 'warn'});
          return
        }
        let expenseFormItems = this.contentList.map(item => {
          return {
            "fillFigure": item.fillFigure,
            "count": item.count,
            "invoiceFileStore": item.invoiceFileStore.map(r => {
              return r.id
            }).join(';'),
            "state": item.state,
            "subjectCode": item.subjectCode,
            "subjectName": item.subjectName,
            "subjectContent": JSON.stringify(item.subjectList.map(r => {
              r.value = item.subjectContent[r.key];
              return r
            })),
            "voucherFileStore": item.voucherFileStore.map(r => {
              return r.id
            }).join(';'),
          }
        });

        let params = {
          "expenseFormItems": expenseFormItems,
          "expenseUser": {id: this.$store.state.user.userInfo.id},
          "fillAmount": this.fillAmount,
          "firstTrials": this.firstTrials.filter(r => {
            return r.checked
          }).map(r => {
            return {
              "id": r.id,
            }
          }),
          "formFileStore": this.formFileStore.map(r => {
            return r.id
          }).join(';'),
          "secondTrials": this.secondTrials.filter(r => {
            return r.checked
          }).map(r => {
            return {
              "id": r.id,
            }
          }),
          "status": index,
          "workOrderCode": this.workOrderCode
        };
        this.$vux.confirm.show({
          title: '提醒',
          content: '请检查数据是否填写完整，提交后无法撤回，是否确定提交？',
          onCancel: () => {

          },
          onConfirm: () => {
            if (this.id) {
              this.$http.put('/expense/api/expenseForm/' + this.id, params).then(res => {
                  this.$vux.toast.show({
                    type: "success",
                    text: '提交成功',
                    onHide: () => {
                      this.$router.back(-1);
                    }
                  })
                }
              )
            } else {
              this.$http.post('/expense/api/expenseForm', params).then(res => {
                  this.$vux.toast.show({
                    type: "success",
                    text: '提交成功',
                    onHide: () => {
                      this.$router.back(-1);
                    }
                  })
                }
              )
            }
          }
        })
      }
      ,
      cancelCommit() {
        this.$vux.confirm.show({
          title: '提醒',
          content: '是否确定放弃操作？',
          onCancel: () => {

          },
          onConfirm: () => {
            this.$router.back(-1);
          }
        })
      }
      ,
    }
    ,
  }
</script>

<style lang="less">
  .createExpenseForm {
    .weui-label {
      text-align-last: justify;
      padding-right: .1rem;
    }
    .vux-label {
      text-align-last: justify;
      padding-right: .1rem;
    }
    .weui-cells{
      line-height: 1.3em;
    }
    .weui-cell {
      line-height: 1.5em;
      padding: 5px 10px;
    }
    .weui-input{
      line-height: 1.5em;
      height: 1.5em;
    }
    .addPerson {
      .weui-cells {
        padding: 15px;
        span {
          font-size: 13px;
          line-height: 13px;
          color: #8b8b8b;
        }
      }
    }
    .clearfix:after {
      content: "020";
      display: block;
      height: 0;
      clear: both;
      visibility: hidden;
    }
    .vux-tab-item .weui-icon-cancel {
      color: #3FBCFC;
      font-size: 19px;
      margin-top: -2px;
    }
    .add-item {
      float: right;
      font-size: 0.12rem;
      height: 0.24rem;
      line-height: 0.24rem;
      margin-top: 0.2rem;
      padding-left: 0.29rem;
      padding-right: 0.1rem;
      background: url('~assets/images2/icon_tianjiafeiyong@2x.png') no-repeat;
      background-size: auto 100%;
    }
    .weui-cells {
      ol {
        padding: 20px 0;
        li {
          width: 25%;
          float: left;
          margin-bottom: 5px;
          .item_box {
            text-align: center;
            position: relative;
            > i {
              position: absolute;
              top: -10px;
              left: 5px;
              color: #C15E67;
            }
            > img {
              height: 50px;
              width: 50px;
            }
            > div {
              text-align: center;
              font-size: 13px;
              padding: 5px 0;
            }
          }
        }
      }
      .vux-selector.weui-cell_select {
        padding: 5px 10px;
        .weui-select {
          height: 1.5em;
          line-height: 1.5em;
        }
      }
      .weui-cell_select .weui-cell__bd:after {
        border-color: #3FBCFC;
        right: 22px;
      }
      .weui-cell_access {
        .child {
          position: absolute;
          right: 35px;
          font-size: 0.13rem;
        }
        .weui-cell__ft:after {
          border-color: #3FBCFC;
          right: 7px;
        }
      }
    }

    .vux-x-input, .weui-cell_select, .vux-x-textarea {
      .weui-cell__bd {
        padding: 2px;
        border: 0.01rem solid #E5E5E5;
        border-radius: 5px;
      }
    }
    .weui-cell__ft {
      .vux-x-input-right-full {
        margin-left: 0px;
        img {
          height: 12px;
          margin-top: 15px;
          margin-left: -12px;
          margin-right: 5px;
        }
      }
    }
    .vux-flexbox {
      .vux-flexbox-item {
        border-radius: 0;
        .weui-btn_primary {
          background: #43A2FE;
          color: #fff;
          .weui_icon_success-circle {
            color: #fff;
          }
        }
        .weui-btn_warn {
          color: #333333;
          background: #fff;
        }
        .weui-btn {
          border-radius: 0;
          &:after {
            border-radius: 0;
          }
        }
      }
    }
  }
</style>
